package com.nopay.cdxphone.ui.ativity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import com.azhon.basic.utils.ActivityManagerUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.base.BaseNoSwipeActivity;
import com.nopay.cdxphone.bean.request.LoginRequest;
import com.nopay.cdxphone.bean.request.SaveCallDataRequest;
import com.nopay.cdxphone.bean.response.LoginResponse;
import com.nopay.cdxphone.bean.response.SaveCallDataResponse;
import com.nopay.cdxphone.dialog.DialogUserAgreementAndPrivacy;
import com.nopay.cdxphone.utils.GsonUtils;
import com.nopay.cdxphone.utils.MemberManager;
import com.nopay.cdxphone.utils.RememberUitls;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import cn.bingoogolapple.swipebacklayout.BGAKeyboardUtil;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.databinding.ActivitySplashBinding;
import com.nopay.cdxphone.db.CallLogBean;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SplashActivity extends BaseNoSwipeActivity<ActivitySplashBinding> {

    private List<CallLogBean> mLocalCallLogData = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setBackgroundDrawable(null);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
//        mLocalCallLogData = DataSupport.findAll(CallLogBean.class);

        boolean isAgree = SPUtils.getInstance().getBoolean(Constants.SP_IS_AGREE, false);

        if(isAgree) {
            MemberManager.setUserTimes(SPUtils.getInstance().getInt(MemberManager.getUserTimesKey(), 0));
            new Handler(getMainLooper()).postDelayed(() -> submitCallLog(), Constants.SPLASH_TIME);
            return;
        }

        new DialogUserAgreementAndPrivacy(SplashActivity.this).setOnAgreementClickListener(new DialogUserAgreementAndPrivacy.OnAgreementClickListener() {
            @Override
            public void openAgree(boolean isUser) {
                startActivity(new Intent(SplashActivity.this, isUser ? UserAgreementActivity.class : PrivacyActivity.class));
            }

            @Override
            public void doAgree(boolean agree) {
                if(agree) {
                    SPUtils.getInstance().put(Constants.SP_IS_AGREE, true);
                    MemberManager.setUserTimes(SPUtils.getInstance().getInt(MemberManager.getUserTimesKey(), 0));
                    new Handler(getMainLooper()).postDelayed(() -> submitCallLog(), Constants.SPLASH_TIME);
                } else {
                    finish();
                }
            }
        }).show();
    }

    private void submitCallLog() {
        if(mLocalCallLogData == null || mLocalCallLogData.size() == 0) {
            gotoNextActivity();
            return;
        }

        CallLogBean callLogBean = mLocalCallLogData.get(0);

        SaveCallDataRequest bean = new SaveCallDataRequest();
        bean.setCallDate(callLogBean.getCallDate());
        bean.setCalledNumber(callLogBean.getCalledNumber());
        bean.setCallingNumber(callLogBean.getCallingNumber());
        bean.setCompany(callLogBean.getCompany());
        bean.setDuration(callLogBean.getDuration());
        bean.setName(callLogBean.getName());
        bean.setPhone(callLogBean.getPhone());
        bean.setStatus(callLogBean.getStatus());
        bean.setTaskId(callLogBean.getTaskId());

        RequestBody body = getRequestBody(bean);
        api.doSaveCallData(body).enqueue(new Callback<SaveCallDataResponse>() {
            @Override
            public void onResponse(@NotNull Call<SaveCallDataResponse> call, @NotNull Response<SaveCallDataResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        callLogBean.delete();
                    }
                }
                mLocalCallLogData.remove(0);
                submitCallLog();
            }

            @Override
            public void onFailure(@NotNull Call<SaveCallDataResponse> call, @NotNull Throwable t) {
                mLocalCallLogData.remove(0);
                submitCallLog();
            }
        });
    }

    private void gotoNextActivity() {
        refreshUser(status -> {
            if (status) {
                BGAKeyboardUtil.closeKeyboard(SplashActivity.this);
                startActivity(new Intent(mCurrentActivity, MainActivity.class));
            } else {
                BGAKeyboardUtil.closeKeyboard(SplashActivity.this);
                startActivity(new Intent(mCurrentActivity, LoginActivity.class));
            }
            finishSplashActivity();
        });

//        long userId = -1;
//        try {
//            userId = SPUtils.getInstance().getLong(Constants.SP_USER_ID, -1L);
//        } catch (Exception e) {
//            userId = SPUtils.getInstance().getInt(Constants.SP_USER_ID, -1);
//        }
//        if(userId != -1) {
//            // TODO 登出
//            api.doLoginOut(userId).enqueue(new Callback<CommonResponse>() {
//                @Override
//                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
//                    if (response.body() != null) {
//                        if (Constants.RESULT_OK.equals(response.body().getCode())) {
//                            SPUtils.getInstance().put(Constants.SP_USER_ID, -1L);
//                            SPUtils.getInstance().put(Constants.SP_USER_NAME, "");
//                            SPUtils.getInstance().put(Constants.SP_PHONE, "");
//                            SPUtils.getInstance().put(Constants.SP_HEAD_URL, "");
//                            SPUtils.getInstance().put(Constants.SP_COMPANY_NAME, "");
//                            SPUtils.getInstance().put(Constants.SP_VIP_STATUS, 0);
//                            SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, "");
//
//                            String deviceId = SPUtils.getInstance().getString(Constants.SP_DEVICE_ID, "");
//                            if("".equals(deviceId)) {
//                                BGAKeyboardUtil.closeKeyboard(SplashActivity.this);
//                                startActivity(new Intent(mCurrentActivity, LoginActivity.class));
//                                return;
//                            }
//
//                            gotoNextActivity();
//                        } else {
//                            ToastUtils.showShort("服务开小差了！请稍后再试");
//                        }
//                    } else {
//                        ToastUtils.showShort("服务开小差了！");
//                    }
//                }
//
//                @Override
//                public void onFailure(Call<CommonResponse> call, Throwable t) {
//                    ToastUtils.showShort(SplashActivity.this.getResources().getString(R.string.call_api_error));
//                }
//            });
//        } else {
//
//        }
    }

    private void finishSplashActivity() {
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        ActivityManagerUtils.getInstance().finishActivity(SplashActivity.this);
    }

    private void refreshUser(OnCheckLoginStatusListener listener) {
        boolean isRemember = SPUtils.getInstance().getBoolean(Constants.SP_IS_REMEMBER, true);
        if(!isRemember) {
            listener.loginStatus(false);
            return;
        }

        String[] loginInfo = RememberUitls.getRemember();
        if(loginInfo.length < 2) {
            listener.loginStatus(false);
            return;
        }

        String account = loginInfo[0];
        String password = loginInfo[1];
        if(TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {
            listener.loginStatus(false);
            return;
        }

        LoginRequest bean = new LoginRequest();
        bean.setPhone(account);
        bean.setPassword(password);
        bean.setEquipmentId(SPUtils.getInstance().getString(Constants.SP_DEVICE_ID, ""));

        //配置请求对象结束
        RequestBody body = getRequestBody(bean);
        api.doLogin(body).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        long userId = response.body().getData().getId();
                        String userName = response.body().getData().getUserName();
                        String phone = response.body().getData().getPhone();
                        String headUrl = response.body().getData().getHeadUrl();
                        String companyName = response.body().getData().getCompanyName();
                        int status = response.body().getData().getStatus();
                        String memberLevel = response.body().getData().getMemberLevel();
                        String invalidTime = response.body().getData().getInvalidTime();
                        String createTime = response.body().getData().getCreateTime();
                        SPUtils.getInstance().put(Constants.SP_USER_ID, userId);
                        SPUtils.getInstance().put(Constants.SP_USER_NAME, userName);
                        SPUtils.getInstance().put(Constants.SP_PHONE, phone);
                        SPUtils.getInstance().put(Constants.SP_HEAD_URL, headUrl);
                        SPUtils.getInstance().put(Constants.SP_COMPANY_NAME, companyName);
                        SPUtils.getInstance().put(Constants.SP_VIP_STATUS, status);
                        SPUtils.getInstance().put(Constants.SP_VIP_LEVEL, memberLevel);
                        SPUtils.getInstance().put(Constants.SP_VIP_INVALID_TIME, invalidTime);
                        SPUtils.getInstance().put(Constants.SP_ACCOUNT_CREATE_TIME, createTime);

                        listener.loginStatus(true);
                    } else {
//                        ToastUtils.showShort(response.body().getMsg());
                        listener.loginStatus(false);
                    }
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                ToastUtils.showShort(SplashActivity.this.getResources().getString(R.string.call_api_error));
                listener.loginStatus(false);
            }
        });
    }

    protected RequestBody getRequestBody(Object object) {
        String jsonStr = GsonUtils.toJson(object);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr);
    }

    public interface OnCheckLoginStatusListener {

        void loginStatus(boolean status);
    }
}
